﻿using System;
using Jayden.Dll.Minecraft.Interfaces;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace Jayden.Dll.Minecraft.Model
{
	public class Chunk
	{
		private int[] m_Data;

		public Chunk()
		{
			m_Data = new int[16 * 16 * 256];



			for (int x = 0; x < 16; x++)
				for (int z = 0; z < 16; z++)
					this[x, 0, z] = BlockManager.BedRock.Id;

			Random rand = new Random(0);

			for (int y = 1; y <= 4; y++)
			{
				for (int x = 0; x < 16; x++)
					for (int z = 0; z < 16; z++)
					{
						if (rand.Next(y + 2) <= 1)
							this[x, y, z] = BlockManager.BedRock.Id;
						else
							this[x, y, z] = BlockManager.Stone.Id;
					}
			}

			for (int y = 1; y <= 4; y++)
				for (int x = y; x < 16 - y; x++)
					for (int z = y; z < 16 - y; z++)
						this[x, 4 - (y - 1), z] = BlockManager.Glass.Id;

			for (int y = 5; y < 16; y++)
				for (int x = 0; x < 16; x++)
					for (int z = 0; z < 16; z++)
						this[x, y, z] = BlockManager.Stone.Id;
		}

		public int this[int x, int y, int z]
		{
			get
			{
				if (x < 0 || x > 15 || y < 0 || y > 255 || z < 0 || z > 15)
					return 0;
				int offset = x + z * 16 + y * 256;
				return m_Data[offset];
			}
			set
			{
				if (x < 0 || x > 15 || y < 0 || y > 255 ||z < 0 || z > 15)
					return;
				int offset = x + z * 16 + y * 256;
				m_Data[offset] = value;
			}
		}

		public Vector3 Selected = new Vector3(-1, -1, -1);

		public void Render(int layer)
		{
			GL.PushMatrix();
			int baseY = layer * 16;
			for (int y = 0; y < 16; y++)
			{
				GL.PushMatrix();
				for (int x = 0; x < 16; x++)
				{
					GL.PushMatrix();
					for (int z = 0; z < 16; z++)
					{
						int blockId = this[x, y, z];
						if (blockId != BlockManager.Air.Id)
						{
							BlockModel block = BlockManager.Instance[blockId];
							if (block != null && block != BlockManager.Air)
							{
								if (Selected != null && Selected.X == x && Selected.Y == y && Selected.Z == z)
									BlockManager.DebugBlock.Render(this, x, y, z);
								else
									block.Render(this, x, y, z);
							}
						}
						GL.Translate(Vector3.UnitZ);
					}
					GL.PopMatrix();
					GL.Translate(Vector3.UnitX);
				}
				GL.PopMatrix();
				GL.Translate(Vector3.UnitY);
			}
			GL.PopMatrix();
		}
	}
}
